package com.lyh.zone.controller.admin;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageInfo;
import com.lyh.zone.common.base.JsonResult;
import com.lyh.zone.common.enums.MaydayEnums;
import com.lyh.zone.common.utils.MaydayUtil;
import com.lyh.zone.common.utils.WebUtil;
import com.lyh.zone.controller.BaseController;
import com.lyh.zone.dto.AttachmentDTO;
import com.lyh.zone.entity.TbAttachment;
import com.lyh.zone.entity.TbUser;
import com.lyh.zone.service.TbAttachmentService;
import com.lyh.zone.service.TbUserService;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 项目名称：zone
 * 类名称：AttachmentController
 * 类描述：
 */
@RequestMapping("/admin/attachment")
@Controller
public class AttachmentController extends BaseController {

    @Autowired
    private TbAttachmentService attachmentService;

    @Autowired
    private TbUserService userService;

    /**
     * 跳转到附件页面并显示所有图片
     * @param modelAndView
     * @param request
     * @param response
     * @param page
     * @param limit
     * @return
     */
    @GetMapping
    public ModelAndView attachment(ModelAndView modelAndView,
                                   HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "page",defaultValue = "1") int page,
                                   @RequestParam(value = "limit",defaultValue = "18") int limit){
        TbUser user= WebUtil.currentUser(request, response);
        PageInfo<TbAttachment> info=attachmentService.getAttachment(page,limit,user);
        modelAndView.addObject("user",userService.selectById(user));
        modelAndView.addObject("pageInfo",info);
        modelAndView.addObject("attachments",info.getList());
        modelAndView.setViewName("admin/admin_attachment");
        return modelAndView;
    }

    /**
     * 上传附件
     * @param file
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public JsonResult upload(@RequestParam(value = "file")MultipartFile file,
                             HttpServletRequest request,HttpServletResponse response){
        return uploadAttachment(file,request,response);
    }

    /**
     * 上传功能
     * @param file
     * @param request
     * @param response
     * @return
     */
    public JsonResult uploadAttachment(@RequestParam(value = "file") MultipartFile file,
                                       HttpServletRequest request,HttpServletResponse response){
        if (!file.isEmpty()) {
            try {
                // 获取用户目录
                String userPath = System.getProperties().getProperty("user.home") + "/mayday/";
                // 保存目录
                StringBuffer hold = new StringBuffer("upload/");
                // 获取时间，以年月创建目录
                Date date = DateUtil.date();
                hold.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
                File mediaPath = new File(userPath, hold.toString());
                // 如果没有该目录则创建
                if (!mediaPath.exists()) {
                    mediaPath.mkdirs();
                }
                System.out.println("路径++++++" + mediaPath);
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                // 生成文件名称
                String nameSuffix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))
                        .replaceAll(" ", "_").replaceAll(",", "") + format.format(DateUtil.date())
                        + new Random().nextInt(1000);
                // 文件后缀
                String fileSuffix = file.getOriginalFilename()
                        .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                // 上传文件名加后缀
                String fileName = nameSuffix + "." + fileSuffix;

                // 转存文件
                file.transferTo(new File(mediaPath.toString(), fileName));

                // 原图片路径
                StringBuffer originalPath = new StringBuffer();
                originalPath.append(mediaPath.getAbsolutePath()).append("/").append(fileName);
                // 压缩图片路径
                StringBuffer compressPath = new StringBuffer();
                compressPath.append(mediaPath.getAbsolutePath()).append("/").append(nameSuffix).append("_small.")
                        .append(fileSuffix);
                // 压缩图片
                Thumbnails.of(originalPath.toString()).size(256, 256).keepAspectRatio(false).toFile(compressPath.toString());
                // 原图数据库路径
                StringBuffer originalDataPath = new StringBuffer();
                originalDataPath.append("/").append(hold).append(fileName);
                // 压缩图数据库路径
                StringBuffer compressDataPath = new StringBuffer();
                compressDataPath.append("/").append(hold).append(nameSuffix).append("_small.").append(fileSuffix);
                // 添加数据库
                TbAttachment attachment = new TbAttachment();
                attachment.setUid(WebUtil.currentUser(request,response).getId());
                attachment.setPictureName(fileName);
                attachment.setPicturePath(originalDataPath.toString());
                attachment.setPictureType(file.getContentType());
                attachment.setPictureCreateDate(date);
                attachment.setPictureSuffix(new StringBuffer().append(".").append(fileSuffix).toString());
                attachment.setPictureSmallPath(compressDataPath.toString());
                attachment.setPictureWH(MaydayUtil.getImageWh(new File(mediaPath.toString() + "/" + fileName)));
                attachment.setPictureSize(MaydayUtil.parseSize(new File(mediaPath.toString() + "/" + fileName).length()));
                AttachmentDTO attachmentDTO=new AttachmentDTO(attachment.getUid(),attachment.getPictureName(),
                        attachment.getPicturePath(),attachment.getPictureSmallPath(),
                        attachment.getPictureType(),attachment.getPictureCreateDate(),
                        attachment.getPictureSize(),attachment.getPictureSuffix(),
                        attachment.getPictureWH());
                attachmentService.save(attachmentDTO);
            } catch (Exception e) {
                log.error("上传附件错误" + e.getMessage());
                return new JsonResult(false, "系统未知错误");
            }
        } else {
            return new JsonResult(false, "文件不能为空");
        }
        return new JsonResult(true, "上传成功");
    }

    /**
     * 删除附件
     * @param id
     * @param response
     * @param request
     * @return
     */
    @PostMapping("/deleteAttachment")
    @ResponseBody
    public JsonResult deleteAttachment(@RequestParam(value = "id") int id,
                                       HttpServletResponse response,HttpServletRequest request){
        TbAttachment attachment=attachmentService.findById(id);
        try {
            // 获取用户目录
            String userPath = System.getProperties().getProperty("user.home") + "/mayday";
            // 获取文件路径
            String picturePath = attachment.getPicturePath();
            String pictureSmallPath = attachment.getPictureSmallPath();
            File picturePathFile = new File(new StringBuffer(userPath).append(picturePath).toString());
            File pictureSmallPathFile = new File(new StringBuffer(userPath).append(pictureSmallPath).toString());
            if (picturePathFile.isFile() && picturePathFile.exists()) {
                System.gc();
                if (pictureSmallPathFile.delete() && picturePathFile.delete()) {
                    attachmentService.deleteAttachment(id);
                    log.info("删除文件" + attachment.getPictureName() + "成功");
                } else {
                    log.error("删除文件" + attachment.getPictureName() + "失败");
                    return new JsonResult(MaydayEnums.OPERATION_ERROR.isFlag(),
                            MaydayEnums.OPERATION_ERROR.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("删除文件" + attachment.getPictureName() + "失败");
            return new JsonResult(MaydayEnums.ERROR.isFlag(), MaydayEnums.ERROR.getMessage());
        }
        return new JsonResult(MaydayEnums.OPERATION_SUCCESS.isFlag(), MaydayEnums.OPERATION_SUCCESS.getMessage());
    }

    @GetMapping("/viewDetails/{id}")
    public ModelAndView viewDetails(ModelAndView modelAndView,@PathVariable int id){
        TbAttachment attachment=attachmentService.findById(id);
        modelAndView.addObject("attachment",attachment);
        modelAndView.setViewName("admin/part/view_details");
        return modelAndView;
    }
}
